"""
@author: Zhang Wenzhou
@file: userinfo.py
@time: 2023/3/4 0004 15:18:28
"""
from flask import Blueprint, request
from flask_restful import Resource, Api
from model.userdb.userinfo import User
from model.user import StuInfo
from model import db
from libs.response import response_data
from libs.auth import login

userapi_bp = Blueprint("userapi_bp", __name__, url_prefix="/v1")
api = Api(userapi_bp)

class UserView(Resource):
    @login
    def post(self):
        try:
            user = request.json
            username = user.get("username")
            password = user.get("password")
            if username and password:
                 user_obj = User(username=username,
                                password=password)
                 db.session.add(user_obj)
                 db.session.commit()
                 return response_data(message="注册成功")
        except:
            return response_data(code=1, message="注册失败")

    @login
    def get(self):
        id = request.args.get("id")
        if id == '' or not id:
            stu = StuInfo.query.all()
            stu_list = []
            for i in stu:
                # stu_list.append(i.to_json())
                stu_list.append(dict(i))
            return response_data(code=2, data=stu_list, message="获取不到id返回所有！")
        stu = StuInfo.query.get(int(id))
        # stu_dict = {"id":id,"姓名":stu.name,"年龄":stu.age,"性别":stu.sex}
        # print(stu.__dict__)
        if stu:
            # return "查询用户"
            print(dict(stu))
            return response_data(data=dict(stu), message="查询用户信息成功！")
            # return stu_dict
        else:
            return response_data(code=1, message="该用户不存在！")


api.add_resource(UserView, "/user")

class LoginView(Resource):
    def post(self):
        user = request.json
        username = user.get("username")
        password = user.get("password")
        user_obj = User.query.filter_by(username=username,
                                        password=password).first()
        if user_obj:
            print(user_obj)
            return response_data(message="登录成功", data=dict(user_obj))
        else:
            return response_data(code=1, message="登录失败")


api.add_resource(LoginView, "/login")


